package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.ChinaArea;
import com.qianying.entity.UserWorkType;
import com.qianying.entity.WorkType;
import com.qianying.mapper.UserWorkTypeMapper;
import com.qianying.service.UserWorkTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.qianying.service.WorkTypeService;


/**
 * 用户与工种关联服务实现类
 * 作者：check
 */
@Service
public class UserWorkTypeServiceImpl extends ServiceImpl<UserWorkTypeMapper, UserWorkType> implements UserWorkTypeService {

    @Autowired
    UserWorkTypeMapper userWorkTypeMapper;
    @Autowired
    WorkTypeService workTypeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<?> saveUserWorkType(UserWorkType userWorkType, Long userId) {
        if (userWorkType == null) {
            return CommonResult.failed("工种关联信息是空的，不能保存！");
        }

        if (userId == null) {
            return CommonResult.failed("用户Id是空的，不能保存！");
        }
        userWorkType.setUserId(userId);
        // 校验必填项
        if (userWorkType.getWorkTypeId() == null) {
            return CommonResult.failed("工种ID不能为空!");
        }

        // 校验是否已存在关联
        LambdaQueryWrapper<UserWorkType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWorkType::getUserId, userWorkType.getUserId())
                .eq(UserWorkType::getWorkTypeId, userWorkType.getWorkTypeId());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return CommonResult.failed("该用户已关联此工种");
        }

        CommonResult<WorkType> workTypeRes = workTypeService.getById(userWorkType.getWorkTypeId());
        if (!workTypeRes.isSuccess()) {
            return CommonResult.failed("工种不存在！");
        }

        if (workTypeRes.getData().getCertificate() && StringUtils.isBlank(userWorkType.getWorkCertificate())) {
            return CommonResult.failed("该工种需要证书，请上传证书");
        }

        // 设置时间
        userWorkType.setCreateTime(LocalDateTime.now());
        userWorkType.setUpdateTime(LocalDateTime.now());
        userWorkType.setId(null);

        boolean save = save(userWorkType);
        return save ? CommonResult.success("关联成功") : CommonResult.failed("关联失败");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<?> updateUserWorkType(UserWorkType userWorkType) {
        if (userWorkType == null) {
            return CommonResult.failed("工种关联信息是空的，不能保存！");
        }

        if (userWorkType.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }
        if (StringUtils.isBlank(userWorkType.getWorkCertificate())) {
            return CommonResult.failed("证书是空的，不能更新！");
        }

        // 只更新证书和时间
        UserWorkType updateEntity = new UserWorkType();
        updateEntity.setId(userWorkType.getId());
        updateEntity.setWorkCertificate(userWorkType.getWorkCertificate());
        updateEntity.setUpdateTime(LocalDateTime.now());

        boolean update = updateById(updateEntity);
        return update ? CommonResult.success("更新成功") : CommonResult.failed("更新失败或数据未变化");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<?> removeById(Long id) {
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }

        boolean remove = userWorkTypeMapper.deleteById(id) > 0 ? true : false;
        return remove ? CommonResult.success("删除成功") : CommonResult.failed("删除失败");
    }


    @Override
    public CommonResult<List<UserWorkType>> getByUserId(Long userId) {
        if (userId == null) {
            return CommonResult.failed("用户ID不能为空");
        }
// 构建条件查询器
        LambdaQueryWrapper<UserWorkType> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件：用户ID匹配
        queryWrapper.eq(UserWorkType::getUserId, userId)
                // 按创建时间倒序排序，最新关联的记录在前
                .orderByDesc(UserWorkType::getCreateTime);

        // 执行查询
        List<UserWorkType> userWorkTypes = baseMapper.selectList(queryWrapper);

        if (!userWorkTypes.isEmpty()) {
            Map<Long, String> map = workTypeService.IdToNameMap();
            if (!map.isEmpty()) {
                for (UserWorkType userWorkType : userWorkTypes) {

                    if (map.containsKey(userWorkType.getWorkTypeId())) {
                        userWorkType.setWorkTypeName(map.get(userWorkType.getWorkTypeId()));
                    }

                }
            }
        } else {
            return  CommonResult.failed("没有查询到权限记录");
        }

        return CommonResult.success(userWorkTypes);
    }
}
